#include <Windows.h>
#include <iostream>

using namespace std;

void next()
{
    int a = 0;

    while (a++ < 10)
    {
        cout << a << endl;
        Sleep(60);
    }
}

int main()
{
    SHELLEXECUTEINFO info = {0};
    info.cbSize = sizeof(info);
    info.fMask = SEE_MASK_NOCLOSEPROCESS;
    info.hwnd = NULL;
    info.lpVerb = NULL;
    // info.lpFile = "E:/Project/Repositories/cpp/cpp/httpserver/dist/py/dist/pppppp_MinGW@13.2.0_min.exe";
    info.lpFile = "E:/Project/Repositories/cpp/cpp/httpserver/dist/py/dist/ws/ws.exe";
    info.lpParameters = "\"{\\\"allowed_origins\\\": [\\\"http://127.0.0.1:6660\\\"]}\""; // 设置要传递的命令行参数
    // info.lpParameters = NULL;
    info.lpDirectory = NULL;
    info.nShow = SW_SHOW;

    if (ShellExecuteEx(&info))
    {
        HANDLE hChildStdoutRead = NULL;
        HANDLE hChildStdoutWrite = NULL;

        SECURITY_ATTRIBUTES saAttr;
        saAttr.nLength = sizeof(SECURITY_ATTRIBUTES);
        saAttr.bInheritHandle = TRUE;
        saAttr.lpSecurityDescriptor = NULL;

        if (!CreatePipe(&hChildStdoutRead, &hChildStdoutWrite, &saAttr, 0))
        {
            cout << "Failed to create pipe." << endl;
            return 1;
        }

        // 将子进程的标准输出重定向到管道写入端
        SetHandleInformation(hChildStdoutRead, HANDLE_FLAG_INHERIT, 0);
        STARTUPINFO si = {0};
        si.cb = sizeof(STARTUPINFO);
        si.hStdError = hChildStdoutWrite;
        si.hStdOutput = hChildStdoutWrite;
        si.dwFlags |= STARTF_USESTDHANDLES;

        PROCESS_INFORMATION pi = {0};
        if (!CreateProcess(NULL, const_cast<LPSTR>(info.lpFile), NULL, NULL, TRUE, 0, NULL, NULL, &si, &pi))
        {
            cout << "Failed to create process." << endl;
            return 1;
        }

        CloseHandle(hChildStdoutWrite);

        char buffer[4096];
        DWORD bytesRead;

        while (true)
        {
            if (!ReadFile(hChildStdoutRead, buffer, sizeof(buffer), &bytesRead, NULL) || bytesRead == 0)
            {
                break;
            }

            buffer[bytesRead] = ' ';
            cout << buffer;
            // if (strstr(buffer, "12345") != NULL)
            // {
            //     cout << 132 << endl;
            //     next();
            //     break;
            // }
        }

        WaitForSingleObject(pi.hProcess, INFINITE);
        CloseHandle(hChildStdoutRead);
        CloseHandle(pi.hProcess);
        CloseHandle(pi.hThread);
    }
    else
    {
        cout << "Failed to open program." << endl;
    }

    return 0;
}